package com.jiaquyun.jcyx.jetpack.mode

import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.SPStaticUtils
import com.jiaquyun.jcyx.jetpack.api.UserRepository
import com.jiaquyun.jcyx.app.AppConstance
import com.jiaquyun.jcyx.base.BaseViewModel
import com.jiaquyun.jcyx.entity.*
import com.module.lemlin.http.HttpResponseBody
import com.module.lemlin.http.SubscribeViewModel

class UserViewModel(application: Application) : CartViewModel(application) {

    private val mUserRepository = UserRepository()

    val smsLiveData = MutableLiveData<HttpResponseBody<SmsResponse>>()

    val loginLiveDate = MutableLiveData<HttpResponseBody<LoginResponse>>()
    fun smsSend(mobile: String, event: String) {
        setRxLifeScope(SubscribeViewModel(smsLiveData)) {
            mUserRepository.smsSend(mobile, event)
        }
    }

    fun userMobileLogin(mobile: String, captcha: String) {
        val subscribe = object : SubscribeViewModel<LoginResponse>(loginLiveDate) {

            override fun onSuccess(resp: LoginResponse) {
                super.onSuccess(resp.apply { keepUserInfo(data.userinfo) })
            }

            /**
             * 保存用户信息
             * */
            private fun keepUserInfo(userInfo: UserInfo) {
                SPStaticUtils.put(AppConstance.SPS_KEY_TOKEN, userInfo.token)
                SPStaticUtils.put(AppConstance.SPS_KEY_USER_INFO, userInfo.toString())
            }
        }
        setRxLifeScope(subscribe) {
            mUserRepository.userMobileLogin(mobile, captcha)
        }
    }

    var page: Int = 1
    var rows:Int = 20

    val collectGoodsLiveDate = MutableLiveData<HttpResponseBody<CollectGoodsResponse>>()
    fun userCollectList(isLoadMore: Boolean = false) {
        val listener = object : SubscribeViewModel<CollectGoodsResponse>(collectGoodsLiveDate) {
            override fun onSuccess(resp: CollectGoodsResponse) {
                super.onSuccess(resp.apply { loadMore = page > 1 })
                page += 1
            }
        }
        if (!isLoadMore)
            page = 1
        setRxLifeScope(listener) {
            mUserRepository.userCollectList( page.toString(), rows.toString())
        }
    }

    val purchaseGoodsLiveDate = MutableLiveData<HttpResponseBody<PurchaseGoodsResponse>>()
    fun userPurchaseList(isLoadMore: Boolean = false) {
        val listener = object : SubscribeViewModel<PurchaseGoodsResponse>(purchaseGoodsLiveDate) {
            override fun onSuccess(resp: PurchaseGoodsResponse) {
                super.onSuccess(resp.apply { loadMore = page > 1 })
                page += 1
            }
        }
        if (!isLoadMore)
            page = 1
        setRxLifeScope(listener) {
            mUserRepository.userPurchaseList(page.toString(), rows.toString())
        }
    }
}